<?php
declare (strict_types=1);

namespace app\common\model;

use addons\BuilderPlus\facade\Table;
use think\facade\Db;

class Admin extends Base
{
    protected $type = [
        'last_time' => 'timestamp',
    ];

    protected function role(): object
    {
        return $this->hasOne(Role::class, 'id', 'role_id');
    }

    public static function _save($arguments, $options): array
    {
        try {
            $param = $arguments['data'];
            if (!empty($param['id'])) {
                if (!empty($param['password'])) {
                    $param['password'] = md5($param['password']);
                } else {
                    unset($param['password']);
                }
                parent::update($param, ['id' => $param['id']]);
                $group = Db::name('auth_group_access')->where(['uid' => $param['id']])->find();
                if ($group['group_id'] != $param['role_id']) {
                    Db::name('auth_group_access')->where(['uid' => $param['id']])->update(['group_id' => $param['role_id']]);
                }
                Table::trigger('logs', ['type' => 'save', 'param' => $arguments]);
            } else {
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('123456');
                $model = parent::create($param);
                Db::name('auth_group_access')->insert(['uid' => $model->id, 'group_id' => $model->role_id]);
                Logs::adds('后台添加新管理员，用户名【' . $model->admin_name . '】');
            }

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _delete($param, $admin): array
    {
        parent::startTrans();
        try {
            $info = parent::where(['id' => $param['id']])->find();
            if (empty($info)) {
                throw new \Exception('该管理员不存在');
            }
            parent::destroy(['id' => $info->id]);
            if ($admin) {
                Logs::adds('删除管理员【' . $info->id . '】【' . $info->admin_name . '】', $admin->id, $admin->admin_name);
            }
            parent::commit();

            return ['code' => 1, 'msg' => '删除成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function reset($param, $admin, $options): array
    {
        try {
            $param['password'] = md5($param['password'] ?: '123456');
            parent::update(['password' => $param['password']], ['id' => explode(',', $param['id'])]);
            $msg = '重置管理员登录密码，ID【' . $param['id'] . '】';
            Logs::adds($msg, $admin->id, $admin->admin_name);

            return ['code' => 1, 'msg' => '重置成功'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}